const store = {
    devices: [],
    bindings: [],
    nodes: []
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function () {
    // 登录功能
    const loginBtn = document.getElementById('loginBtn');
    const logoutBtn = document.getElementById('logoutBtn');

    loginBtn.addEventListener('click', async function () {
        const password = document.getElementById('password').value;
        try {
            const response = await axios.post('/api/login', {password});
            if (response.data.success) {
                document.getElementById('loginContainer').style.display = 'none';
                document.getElementById('mainContainer').style.display = 'block';
                loadAllData();
                sessionStorage.setItem("isLogin", "true")
            } else {
                showLoginError();
            }
        } catch (error) {
            showLoginError(error.response.data);
        }

        function showLoginError(msg) {
            document.getElementById('loginMessage').style.display = 'block';
            if(!!msg) document.getElementById('loginMessage').innerText = msg
            setTimeout(() => {
                document.getElementById('loginMessage').style.display = 'none';
            }, 3000);
        }
    });

    logoutBtn.addEventListener('click', function () {
        document.getElementById('mainContainer').style.display = 'none';
        document.getElementById('loginContainer').style.display = 'flex';
        document.getElementById('password').value = '';
        sessionStorage.clear()
    });

    // 标签页切换
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function () {
            // 移除所有活动标签
            tabs.forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(tc => tc.classList.remove('active'));

            // 添加活动类
            this.classList.add('active');
            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');

            sessionStorage.setItem("tab", tabId)
        });
    });

    // 模态框控制
    const modal = document.getElementById('modal');
    const closeModalBtn = document.getElementById('closeModal');

    closeModalBtn.addEventListener('click', function () {
        modal.style.display = 'none';
    });

    window.addEventListener('click', function (event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });

    // 全选框控制
    document.querySelectorAll('thead .checkbox-cell input[type="checkbox"]').forEach(em => em.addEventListener('click', function() {
        this.closest('table').querySelectorAll('input[type="checkbox"]').forEach(b => b.checked = this.checked)
    }))

    // 添加按钮事件
    document.getElementById('addNodesBtn').addEventListener('click', showAddNodeModal);

    // 刷新按钮事件
    document.getElementById('refreshDeviceBtn').addEventListener('click', () => loadDevices());
    document.getElementById('refreshBindsBtn').addEventListener('click', () => loadbinds());
    document.getElementById('refreshNodesBtn').addEventListener('click', () => loadnodes());

    // 批量删除
    document.getElementById("deleteBindsBtn").addEventListener('click', () => deleteBings())
    document.getElementById("deleteNodesBtn").addEventListener('click', () => deleteNodes())

    if (sessionStorage.getItem("isLogin") == "true") {
        document.getElementById('loginContainer').style.display = 'none';
        document.getElementById('mainContainer').style.display = 'block';
        loadAllData();
    }

    if(sessionStorage.getItem('tab')){
        document.querySelector('.tab[data-tab="'+ sessionStorage.getItem('tab') +'"]').click()
    }
});

// 加载所有数据
async function loadAllData() {
    await loadDevices(1);
    await loadbinds(1);
    await loadnodes(1);
}

// 加载devices设备
async function loadDevices() {
    try {
        const response = await axios.get(`/api/devices`);
        store.devices = response.data?.data || []
        renderDevices();
    } catch (error) {
        console.error('加载devices设备失败:', error);
        alert(error.response.data);
    }
}

// 加载S5绑定
async function loadbinds() {
    try {
        const response = await axios.get(`/api/bindings/list`);
        store.bindings = response.data.data || []
        renderbinds()
    } catch (error) {
        console.error('加载S5绑定失败:', error);
        alert(error.response.data);
    }
}

// 加载S5节点
async function loadnodes() {
    try {
        const response = await axios.get(`/api/passwall/list`);
        store.nodes = response.data.data || []
        rendernodes();
    } catch (error) {
        console.error('加载S5节点失败:', error);
        alert(error.response.data);
    }
}

// 批量删除绑定
async function deleteBings(){
    if (confirm('确定要删除所有选中的绑定吗？')) {
        try {
            let macs = []
            for(let em of Array.from(document.querySelectorAll('.binding-checkbox:checked'))){
                macs.push(em.dataset.id)
            }
            if(macs?.length){
                await axios.delete(`/api/bindings/delete?mac=` + macs.join(","));
                loadbinds();
                loadDevices()
            }
        } catch (error) {
            console.error('删除节点失败:', error);
            alert(error.response.data);
        }
    }
}

// 批量删除代理
async function deleteNodes(){
    if (confirm('确定要删除所有选中的代理节点吗？')) {
        try {
            let nodeIds = []
            for(let em of Array.from(document.querySelectorAll('.node-checkbox:checked'))){
                nodeIds.push(em.dataset.id)
            }
            if(nodeIds?.length) {
                await axios.get(`/api/passwall/delete?id=${nodeIds.join(',')}`);
                loadnodes();
            }
        } catch (error) {
            console.error('删除节点失败:', error);
            alert(error.response.data);
        }
    }
}

// 显示添加绑定模态框
async function showAddBindingModal(binding) {
    try {
        const modal = document.getElementById('modal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');

        modalTitle.textContent = '添加S5设备绑定';

        let options = []
        for(let node of store.nodes){
            const em = document.createElement("option")
            em.value = node.name + '[节点ID：'+ node.id +']'
            options.push(em.outerHTML)
        }
        let node = ''
        if(!!binding.nodeId) node = `${binding.nodeName}[节点ID：${binding.nodeId}]`

        modalBody.innerHTML = `
                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalBindingName">输入名称</label>
                            <input type="text" id="modalBindingName" value="${binding.deviceName}">
                        </div>
                        <div class="form-group">
                            <label for="modalBindingMac">选择设备</label>
                            <input id="modalBindingMac" class="form-select" value="${binding.deviceMac}"/>
                        </div>
                        <div class="form-group">
                            <label for="modalBindingNode">选择代理节点</label>
                            <input id="modalBindingNode" class="form-select" list="node-list" value="${node}">
                            <datalist id="node-list">`+ options.join("") +`</datalist>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-success" id="saveBindingBtn"><i class="fas fa-save"></i> 保存绑定</button>
                        <button class="btn" id="cancelBindingBtn">取消</button>
                    </div>
                `;

        modal.style.display = 'block';

        document.getElementById('saveBindingBtn').addEventListener('click', async function () {
            const name = document.getElementById('modalBindingName').value;
            const mac = document.getElementById('modalBindingMac').value;
            const arr = document.getElementById('modalBindingNode').value.match(/\[节点ID：(\w+)\]/)
            if(arr?.length < 2) return
            const nodeId = arr[1]
            const status = true

            if (!mac || !nodeId) {
                alert('请选择设备和节点');
                return;
            }

            try {
                await axios.post(`/api/bindings/save`, {name, mac, nodeId, status});
                modal.style.display = 'none';
                await loadDevices();
                await loadbinds();
                await loadnodes();
            } catch (error) {
                console.error('添加设备绑定失败:', error);
                alert(error.response.data);
            }
        });

        document.getElementById('cancelBindingBtn').addEventListener('click', function () {
            modal.style.display = 'none';
        });
    } catch (error) {
        console.error('加载添加绑定表单失败:', error);
        alert('加载表单失败，请重试');
    }
}

// 显示添加节点模态框
function showAddNodeModal(node) {
    const modal = document.getElementById('modal');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');

    modalTitle.textContent = '添加S5代理节点';

    modalBody.innerHTML = `
                <div class="form-row">
                    <div class="form-group">
                        <label for="modalNodeName">节点名称</label>
                        <input type="text" id="modalNodeName" placeholder="例如: 上海节点" value="${node.name || ''}">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="modalNodeAddress">服务器地址</label>
                        <input type="text" id="modalNodeAddress" placeholder="例如: s5.example.com" value="${node.address || ''}">
                    </div>
                    <div class="form-group">
                        <label for="modalNodePort">端口</label>
                        <input type="number" id="modalNodePort" placeholder="例如: 1080" value="${node.port || ''}">
                    </div>
                    <div class="form-group">
                        <label for="modalNodeUsername">用户名 (可选)</label>
                        <input type="text" id="modalNodeUsername" placeholder="用户名" value="${node.username || ''}">
                    </div>
                    <div class="form-group">
                        <label for="modalNodePassword">密码 (可选)</label>
                        <input type="password" id="modalNodePassword" placeholder="密码" value="${node.password || ''}">
                    </div>
                </div>
                <div class="form-actions">
                    <button class="btn btn" id="pasteNodeBtn">一键粘贴</button>
                    <button class="btn btn-success" id="saveNodeBtn" data-id="${node.id || ''}"><i class="fas fa-save"></i> 保存节点</button>
                </div>
            `;

    modal.style.display = 'block';

    document.getElementById('saveNodeBtn').addEventListener('click', async function () {
        const id = this.dataset.id || ''
        const name = document.getElementById('modalNodeName').value;
        const address = document.getElementById('modalNodeAddress').value;
        const port = document.getElementById('modalNodePort').value;
        const username = document.getElementById('modalNodeUsername').value;
        const password = document.getElementById('modalNodePassword').value;

        if (!name || !address || !port) {
            alert('请填写必填字段');
            return;
        }

        try {
            await axios.post(`/api/passwall/save`, [{
                id,
                name,
                address,
                port: parseInt(port),
                username,
                password
            }]);
            modal.style.display = 'none';
            loadnodes();
        } catch (error) {
            console.error('添加代理节点失败:', error);
            alert(error.response.data);
        }
    });

    document.getElementById('pasteNodeBtn').addEventListener('click', async function () {
        // 61.171.19.78|18188|11lllxhs|0623|2025-07-23上-海
        try {
            // 请求剪贴板读取权限
            const clipboardItems = await navigator.clipboard.read();

            for (const clipboardItem of clipboardItems) {
                // 尝试获取文本内容
                for (const type of clipboardItem.types) {
                    if (type === 'text/plain') {
                        const blob = await clipboardItem.getType(type);
                        const text = await blob.text();
                        const lines = text.split('\n').filter(r => r.trim().split('|')?.length > 1)
                        if(!lines?.length)return
                        for(let line of lines){
                            const arr = line.split('|')
                            document.getElementById('modalNodeAddress').value = arr[0]
                            document.getElementById('modalNodePort').value = Number(arr[1])
                            if(arr.length > 2)document.getElementById('modalNodeUsername').value = arr[2]
                            if(arr.length > 3)document.getElementById('modalNodePassword').value = arr[3]
                            if(arr.length > 4)document.getElementById('modalNodeName').value = arr[4]
                        }
                        return;
                    }
                }
            }

            alert('剪贴板中没有文本内容');
        } catch (err) {
            console.error('无法读取剪贴板:', err);
            alert('无法访问剪贴板，请确保已授予权限');
        }
    });
}

// 渲染devices设备列表
function renderDevices() {
    const devicesList = document.getElementById('devicesList');
    devicesList.innerHTML = '';

    store.devices.forEach(device => {
        const row = document.createElement('tr');
        row.innerHTML = `
                    <td class="checkbox-cell"><input type="checkbox" class="device-checkbox" data-id="${device.mac}"></td>
                    <td>${device.name}</td>
                    <td>${device.mac}</td>
                    <td>${device.ip}</td>
                    <td>${device.type === 'static' ? `静态[<a href="javascript:void(0)" class="unbind" data-id="${device.mac}">解绑</a>]` : '动态'}</td>
                    <td><span class="status ${device.status === 'online' ? 'status-online' : 'status-offline'}">${device.status === 'online' ? '在线' : '离线'}</span></td>
                    <td>
                        ${device.type === 'static' ? '' : `<button class="btn add-device btn-success" data-id="${device.mac}"><i class="fas fa-plus"></i>绑定代理</button>`}
                    </td>
                `;
        devicesList.appendChild(row);
    });

    // 添加事件监听
    document.querySelectorAll('.add-device').forEach(btn => {
        btn.addEventListener('click', function () {
            const device = store.devices.find(r => r.mac === this.dataset.id)
            showAddBindingModal({deviceName: device.name, deviceMac: device.mac, deviceIp: device.ip})
        });
    });

    document.querySelectorAll("td a.unbind").forEach(btn => {
        btn.addEventListener("click", async function () {
            try {
                const device = store.devices.find(r => r.mac === this.dataset.id)
                await axios.post("/api/static/bind", {mac: device.mac})
                loadDevices()
            } catch (error) {
                console.error('绑定/解绑失败:', error);
                alert(error.response.data)
            }
        })
    })
}

// 渲染S5绑定列表
function renderbinds() {
    const bindingsList = document.getElementById('bindsList');
    bindingsList.innerHTML = '';

    store.bindings.forEach(binding => {
        const row = document.createElement('tr');
        row.innerHTML = `
                    <td class="checkbox-cell"><input type="checkbox" class="binding-checkbox" data-id="${binding.deviceMac}"></td>
                    <td>${binding.deviceName}</td>
                    <td>${binding.deviceMac}</td>
                    <td>${binding.deviceIp}</td>
                    <td>${binding.nodeName}</td>
                    <td>${binding.remarks}</td>
                    <td><span class="status ${binding.status ? 'status-online' : 'status-offline'}">${binding.status ? '已绑定' : '未激活'}</span></td>
                    <td>
                        <button class="btn edit-binding" data-id="${binding.deviceMac}"><i class="fas fa-edit"></i>编辑</button>
                        <button class="btn btn-danger delete-binding" data-id="${binding.deviceMac}"><i class="fas fa-trash-alt"></i>删除</button>
                    </td>
                `;
        bindingsList.appendChild(row);
    });

    // 添加事件监听
    document.querySelectorAll('.edit-binding').forEach(btn => {
        btn.addEventListener('click', async function () {
            const mac = this.dataset.id
            const binding = store.bindings.find(r => r.deviceMac === mac)
            if(!!binding.deviceMac){
                showAddBindingModal(binding)
            }
        });
    });

    // 添加事件监听
    document.querySelectorAll('.delete-binding').forEach(btn => {
        btn.addEventListener('click', async function () {
            const mac = this.dataset.id
            if (confirm('确定要删除此绑定吗？')) {
                try {
                    await axios.get(`/api/bindings/delete?mac=${mac}`);
                    loadbinds();
                } catch (error) {
                    console.error('删除绑定失败:', error);
                    alert(error.response.data);
                }
            }
        });
    });
}

// 渲染S5节点列表
function rendernodes() {
    const nodesList = document.getElementById('nodesList');
    nodesList.innerHTML = '';

    store.nodes.forEach(node => {
        const row = document.createElement('tr');
        row.innerHTML = `
                    <td class="checkbox-cell"><input type="checkbox" class="node-checkbox" data-id="${node.id}"></td>
                    <td>${node.name}</td>
                    <td>${node.address}</td>
                    <td>${node.port}</td>
                    <td>${node.username || '-'}</td>
                    <td>${node.password || '-'}</td>
                    <td>${node.devices?.length || 0} 设备</td>
                    <td>
                        <button class="btn edit-node" data-id="${node.id}"><i class="fas fa-edit"></i>编辑</button>
                        <button class="btn btn-danger delete-node" data-id="${node.id}"><i class="fas fa-trash-alt"></i>删除</button>
                    </td>
                `;
        nodesList.appendChild(row);
    });

    document.querySelectorAll('.edit-node').forEach(btn => {
        btn.addEventListener('click', async function(){
            const node = store.nodes.find(r => r.id === this.dataset.id)
            if(node.id != '')showAddNodeModal(node)
        })
    })

    // 添加事件监听
    document.querySelectorAll('.delete-node').forEach(btn => {
        btn.addEventListener('click', async function () {
            const nodeId = this.dataset.id;
            if (confirm('确定要删除此代理节点吗？')) {
                try {
                    await axios.get(`/api/passwall/delete?id=${nodeId}`);
                    loadnodes();
                } catch (error) {
                    console.error('删除节点失败:', error);
                    alert(error.response.data);
                }
            }
        });
    });
}